package com.lotter.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendSMSUtil {
	
	// 记录日志 
	private static final Logger logger = LoggerFactory.getLogger(SendSMSUtil.class);
    

	
	private static final String SMS_USER = "momolj";
	
	private static final String SMS_PASSWORD = "a123456";
	
	private static final String SMS_URL = "http://service.winic.org/sys_port/gateway/index.asp";
	
	public static Boolean send(String mobile,String content) throws RuntimeException,
	         UnsupportedEncodingException,IOException{
		
		if(StringUtil.isBlank(mobile))
			throw new RuntimeException("手机号码不能为空");
		
		if (mobile.trim().length() != 11) 
			throw new RuntimeException("手机号码位数不是11位");
		
		if (!mobile.matches("(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}"))
			throw new RuntimeException( "手机号码不符合规则");
		
		StringBuilder sb = new StringBuilder();

		//以下是参数
		sb.append("id=").append(URLEncoder.encode(SMS_USER, "gb2312"));
		sb.append("&pwd=").append(SMS_PASSWORD);
		sb.append("&to=").append(mobile);
		sb.append("&content=").append(URLEncoder.encode(content, "gb2312")); 
		sb.append("&time=").append(DateUtil.date2String(new Date()));

		String message = post(SMS_URL,sb.toString());
		logger.info(message + "send message" + content);
		return sendIsOk(message);
	}
	
	
    private static String post(String path,String params) throws RuntimeException, IOException{   
		   BufferedReader in=null;  
		   PrintWriter out=null; 
		   HttpURLConnection httpConn = null ;
		   try {                  
			   URL url=new URL(path); 
			   httpConn=(HttpURLConnection)url.openConnection(); 
			   httpConn.setRequestMethod("POST"); 
			   httpConn.setDoOutput(true);
			   httpConn.setDoInput(true);
			   httpConn.setUseCaches(false);
			   
			   out=new PrintWriter(httpConn.getOutputStream()); 
			   out.println(params); 
			   out.flush(); 
			     
			   if(httpConn.getResponseCode()==HttpURLConnection.HTTP_OK){   
				    StringBuffer content=new StringBuffer(); 
				    String tempStr="";    
				    in=new BufferedReader(new InputStreamReader(httpConn.getInputStream()));    
				    while((tempStr=in.readLine())!=null){    
				       content.append(tempStr);    
				    }    
				    System.out.println(content);
				    return content.toString();    
			    }else{    
			    	throw new RuntimeException("请求出现了问题!");    
			    }    
		    } catch (IOException e) {    
		    	e.printStackTrace();    
		    }finally{    
			    in.close();    
			    out.close();    
			    httpConn.disconnect();    
		    }    
		    return null;    
		}    
    
    
        //发送短信是否成功
       private static Boolean sendIsOk(String message){
        	//失败   -04/Send:0/Consumption:0/Tmoney:0/sid:
        	if(StringUtil.isBlank(message)){
        		return false;
        	}
        	String[] strTemp = message.split("/");
        	for(String str :strTemp){
        		String[] temp = str.split(":");
        		if(temp.length <2){
        			continue;
        		}
        		if(temp[0].equals("send")){
        			if(Integer.parseInt(temp[1]) < 1){
        				return false;
        			}else{
        				return true;
        			}
        		}
        	}
        	return false;
        }
		     
	    public static void main(String[] args) throws Exception {    
		    String resMessage=SendSMSUtil.post("http://service.winic.org/sys_port/gateway/index.asp", "id=momolj&pwd=a123456&to=1500021660711&content="+URLEncoder.encode("恭喜发财","gb2312")+"&time="+new Date());    
		    System.out.println(resMessage);    
	    }    
}
